package com.darlingda.dahaigui.service.impl;

import com.darlingda.dahaigui.constant.AIConst;
import com.darlingda.dahaigui.manager.AIManager;
import com.darlingda.dahaigui.model.ChatRoom;
import com.darlingda.dahaigui.service.ChatService;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessage;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zheng
 * @Date: 2025/03/28 15:38
 */
@Service
public class ChatServiceImpl implements ChatService {
    
    @Resource
    private AIManager aiManager;
    
    // 全局消息映射
    final Map<Long, List<ChatMessage>> globalMessagesMap = new HashMap<>();
    
    
    @Override
    public String doChat(long roomId, String message) {
        // 系统预设
        final String systemPrompt = AIConst.SYSTEM_PROMPT;
        // 1.准备消息列表（关联历史上下文）
        final ChatMessage systemMessage = ChatMessage.builder().role(ChatMessageRole.SYSTEM).content(systemPrompt).build();
        final ChatMessage userMessage = ChatMessage.builder().role(ChatMessageRole.USER).content(message).build();
        
        List<ChatMessage> messages = new ArrayList<>();
        // 首次开始时，需要初始化消息列表，并且额外添加系统消息到记录中
        if (!AIConst.GAME_BEGIN.equals(message) && globalMessagesMap.isEmpty()) {
            throw new RuntimeException("请先开始游戏！");
        }
        if (AIConst.GAME_BEGIN.equals(message) && !globalMessagesMap.containsKey(roomId)) {
            globalMessagesMap.put(roomId, messages);
            messages.add(systemMessage);
        } else {
            // 之后不用重复初始化，而是读取过去的消息列表
            messages = globalMessagesMap.get(roomId);
        }
        messages.add(userMessage);
        
        // 2.调用 AI
        String answer = aiManager.doChat(messages);
        final ChatMessage assistantMessage = ChatMessage.builder().role(ChatMessageRole.ASSISTANT).content(answer).build();
        messages.add(assistantMessage);
        
        // 3.返回消息
        if (answer.contains(AIConst.GAME_OVER)) {
            globalMessagesMap.remove(roomId);
        }
        return answer;
    }
    
    @Override
    public List<ChatRoom> getChatRoomList() {
        List<ChatRoom> chatRoomList = new ArrayList<>();
        for (Map.Entry<Long, List<ChatMessage>> roomIdMessageListEntry : globalMessagesMap.entrySet()) {
            ChatRoom chatRoom = new ChatRoom();
            chatRoom.setRoomId(roomIdMessageListEntry.getKey());
            chatRoom.setChatMessageList(roomIdMessageListEntry.getValue());
            chatRoomList.add(chatRoom);
        }
        return chatRoomList;
    }
    
    
}
